package com.xlongwei.todays.dao;

import java.util.Collections;
import java.util.List;

import org.noear.solon.Utils;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.data.annotation.Cache;
import org.noear.solon.data.annotation.CacheRemove;
import org.noear.solon.data.annotation.Transaction;
import org.noear.solon.data.sql.SqlBuilder;

import com.xlongwei.todays.config.MySqlUtils;
import com.xlongwei.todays.model.Mydo;
import com.xlongwei.todays.view.MydoQuery;

@Component
public class MydoDao {
    @Inject
    MySqlUtils sqlUtils;

    @Cache(key = "mydo.${userid}.${todoid}")
    public Mydo findByUseridAndTodoid(Integer userid, Integer todoid) {
        return sqlUtils
                .sql("select mydoid,userid,todoid,today,start,status from t_mydo where userid=? and todoid=?", userid,
                        todoid)
                .queryRow(Mydo.class);
    }

    @Transaction
    @CacheRemove(keys = "mydo.${},mydo.${row.userid}.${row.todoid}", tags = "mydos")
    public Integer create(Mydo row) {
        assert row.getMydoid() == null;
        Object key = sqlUtils
                .sql("insert into t_mydo(userid,todoid,today,start,status) values(?,?,?,?,?)",
                        row.getUserid(), row.getTodoid(), row.getToday(), row.getStart(), row.getStatus())
                .updateReturnKey();
        return Integer.parseInt(key.toString());
    }

    @Cache(key = "mydo.${mydoid}")
    public Mydo retrieve(Integer mydoid) {
        return sqlUtils.sql("select mydoid,userid,todoid,today,start,status from t_mydo where mydoid=?", mydoid)
                .queryRow(Mydo.class);
    }

    @Transaction
    @CacheRemove(keys = "mydo.${row.mydoid},mydo.${row.userid}.${row.todoid}", tags = "mydos")
    public Integer update(Mydo row) {
        assert row.getMydoid() != null;
        return sqlUtils.sql("update t_mydo set userid=?,todoid=?,today=?,start=?,status=? where mydoid=?",
                row.getUserid(), row.getTodoid(), row.getToday(), row.getStart(), row.getStatus(), row.getMydoid())
                .update();
    }

    @Cache(tags = "mydos")
    public List<Mydo> list(MydoQuery query) {
        SqlBuilder sqlSpec = new SqlBuilder();
        sqlSpec.append("select mydoid,userid,todoid,today,start,status from t_mydo where 1=1");
        sqlSpec.appendIf(query.getUserid() != null, " and userid=?", query.getUserid());
        sqlSpec.appendIf(query.getTodoid() != null, " and todoid=?", query.getTodoid());
        sqlSpec.appendIf(query.getToday() != null, " and today=?", query.getToday());
        sqlSpec.appendIf(Utils.isNotBlank(query.getStatus()), " and status=?", query.getStatus());
        sqlSpec.appendIf(query.getUserid() != null, " order by start");
        List<Mydo> list = sqlUtils.sql(sqlSpec).queryRowList(Mydo.class);
        return list != null ? list : Collections.emptyList();
    }
}
